package org.gurms.common.validate;

import java.util.List;

import org.gurms.common.util.ReflectionUtil;
import org.springframework.stereotype.Service;

@Service
public class GurmsValidator implements Validation {

	public String valid(String clzName, String[] props, Object o){
		List<GurmsValidRule> rules = GurmsValidConfig.getBeanRules(clzName, props);
		StringBuffer sb = new StringBuffer();
		
		for(GurmsValidRule g : rules){
			g.setValue((String)ReflectionUtil.getFieldValue(o, g.getField()));
			boolean tmp = g.validField();
			if(!tmp){
				sb.append(g.getMsg());
			}
		}
		return sb.toString();
	}
	
	public String script(String clzName, String[] props){
		List<GurmsValidRule> rules = GurmsValidConfig.getBeanRules(clzName, props);
		
		GurmsValidRule temp = new GurmsValidRule();
		for(GurmsValidRule g : rules){
			temp.addScript(g);
		}
		StringBuffer script = new StringBuffer();
		script.append("function _validForm(){");
		script.append(temp.getScript());
		script.append("var validform;");
		script.append("var forms=document.getElementsByTagName('form');");
		script.append("if(forms&&forms.length) for(var i=0; i<forms.length; i++){");
		script.append("if(forms[i].id.indexOf('valid_')==0){validform=forms[i];break;}}");
		script.append("return LiveValidationForm.getInstance(validform).validForm();}");
		return script.toString();
	}
}
